import { createRouter, createWebHashHistory } from "vue-router";
import { reactive } from "vue";
import store from "../store/index.js";

const routes = [
  {
    path: "/",
    name: "layout",
    component: () => import("../Layout/index.vue"),
    redirect: "/Home",
    children: [
      {
        path: "/Home",
        name: "home",
        component: () => import("../views/Home/index.vue"),
      },
    ],
  },
  {
    path: "/Login",
    component: () => import("../views/Login/index.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由前置守卫;
router.beforeEach((to, from, next) => {
  if (to.name == "home") {
    setTimeout(() => {
      menuRouter(
        JSON.parse(localStorage.getItem("tabList")) ||
          store.state.layout.tabList ||
          []
      );
    }, 500);
  }
  //此项目没有mock出token这里记得写是否有token那些的权限哦 next()方法要根据权限哦
  next();
});

function menuRouter(menu) {
  const newmenu = reactive([]);
  menu.forEach((item) => {
    if (item.children) {
      menuRouter(item.children);
    } else {
      let url = item.path.substr(1);
      item.component = () => import(`../views/${url}/index.vue`);
      newmenu.push(item);
    }
  });
  newmenu.forEach((item) => {
    router.addRoute("layout", item);
  });
}

menuRouter(
  JSON.parse(localStorage.getItem("tabList")) ||
    store.state.layout.tabList ||
    []
);

export default router;
